// Copyright Epic Games, Inc. All Rights Reserved.

#include "TetrisPawn.h"
#include "TetrisBackGround.h"
#include "TetrisBlock.h"
#include "TetrisView.h"
#include "Block.h"
#include "Kismet/GameplayStatics.h"
#include "GameFramework/PlayerController.h"
#include "Engine/World.h"

ATetrisPawn::ATetrisPawn(const FObjectInitializer& ObjectInitializer) 
	: Super(ObjectInitializer)
{
	AutoPossessPlayer = EAutoReceiveInput::Player0;
}

void ATetrisPawn::BeginPlay()
{
	Super::BeginPlay();
	View = GetWorld()->SpawnActor<ATetrisView>();
	BackGround = new TetrisBackGround;
	block = new Block;
	block->SetBackGround(BackGround);
	block->SetstartDrawPosition();
	block->NewTurn();
	block->SetBlock();
}

void ATetrisPawn::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);

	TickTime += DeltaSeconds;
	if (TickTime > 1.0f)
	{
		block->Drop();
		TickTime = 0;
	}
	DrawMap();
}

void ATetrisPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	PlayerInputComponent->BindAction("Left", EInputEvent::IE_Pressed,this, &ATetrisPawn::MoveLeft);
	PlayerInputComponent->BindAction("Right", EInputEvent::IE_Pressed,this, &ATetrisPawn::MoveRight);
	PlayerInputComponent->BindAction("Rotate", EInputEvent::IE_Pressed,this, &ATetrisPawn::Rotate);
	PlayerInputComponent->BindAction("Down", EInputEvent::IE_Pressed,this, &ATetrisPawn::Down);
	PlayerInputComponent->BindAction("Exit", EInputEvent::IE_Pressed,this, &ATetrisPawn::Exit);
}


void ATetrisPawn::MoveLeft()
{
		block->MoveLeft();
}

void ATetrisPawn::MoveRight()
{
		block->MoveRight();
}

void ATetrisPawn::Rotate()
{
		block->Rotate();
}

void ATetrisPawn::Down()
{
		block->Drop();
}

void ATetrisPawn::Exit()
{
		delete BackGround;
		delete block;
		UKismetSystemLibrary::QuitGame(this, nullptr, EQuitPreference::Quit, true);
}

void ATetrisPawn::DrawMap()
{
	TArray<int> Data= BackGround->GetArray();
	if (Data.Num() == 0) return;
	else
	{
		for (int i = 0; i < Data.Num(); i++)
		{
			int temp = i;
			View->SetColor(i, Data[i]);
		}
	}
	Data.Empty();
}